<template>
  <el-form>
    <el-form-item :label="$t('profile.oldPassword')">
      <el-input v-model.trim="user.oldPassword" type="password"/>
    </el-form-item>
    <el-form-item :label="$t('profile.newPassword')">
      <el-input v-model.trim="user.password" type="password"/>
    </el-form-item>
    <el-form-item :label="$t('profile.confirmPassword')">
      <el-input v-model.trim="user.confirmPassword" type="password"/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">{{ $t('profile.updatePassword') }}</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { updatePassword } from '@/api/user'

export default {
  props: {
    user: {
      type: Object,
      default: () => {
        return {
          userId: 0,
          oldPassword: '',
          password: '',
          confirmPassword: ''
        }
      }
    }
  },
  methods: {
    submit() {
      this.user.userId = this.$store.getters.id
      updatePassword(this.user).then(async response => {
        const data = response.data
        if (data >= 1) {
          this.$message({
            message: 'User password has been updated successfully',
            type: 'success',
            duration: 5 * 1000
          })
          await this.$store.dispatch('user/logout')
          this.$router.push(`/login?redirect=${this.$route.fullPath}`)
        }
      })
    }
  }
}
</script>
